#!/bin/sh
#
# Build a patch agains the current FreeBSD ports to request an exp-run.
#
# All ports under VCS in the current directory that exists in the PORTSDIR
# directory are processed.
#

PORTSDIR="/var/cache/portshaker/ports"
EXPORTDIR="/tmp/exp-run-export"

usage()
{
    echo "usage: $0 patch"
}

if [ $# -ne 1 ]; then
    usage
    exit 1
fi

patch="$1"

:>${patch}

rm -rf "${EXPORTDIR}"

echo "Generating patch:"

find . -maxdepth 3 -name Makefile | sed 's:^./::' | while read file_name; do
    if [ -e "${PORTSDIR}/${file_name}" ]; then
	port=`dirname "${file_name}"`
	if [ -d "${port}/.svn" ]; then
	    case `svnversion "${port}"` in
		*M)  echo "FATAL:   ${port} has local modifications." >&2 ; exit 1;;
		*:*) echo "WARNING: ${port} should be updated" >&2 ;;
	    esac
	    mkdir -p "${EXPORTDIR}/`dirname ${port}`"
	    svn export "${port}" "${EXPORTDIR}/${port}" > /dev/null
	    (cd "${EXPORTDIR}" && diff -NrU 0 --ignore-matching-lines='\$\(FreeBSD\|Id\|MCom\)' "${PORTSDIR}/${port}" "${port}") >> ${patch} && echo -n "." || echo -n "U"
	fi
    fi
done
rm -rf "${EXPORTDIR}"

echo
echo "done"

awk '
    BEGIN {
	lil = 0;
	lib = 0;
	lrl = 0;
	lrb = 0;
    }
    /^@@/ {
	l=NR;
    }
    /^-.*\$FreeBSD/ {
	lrl = NR;
	lrb = l;
    }
    /^\+.*\$FreeBSD/ {
	lil = NR;
	lib = l;
    }
    {
	if ((lib > 0) && (lib == lrb)) {
	    print "Please manually review patch around line " lib "  (VCS information removed line " lrl" and inserted line "lil")";
	    lib = 0;
	}
    }' ${patch}

exit 0
